﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GalaSoft.MvvmLight;
using System.ComponentModel;

namespace Medecine.Interface.Main
{
	/// <summary>
	/// <para>ViewModel base class with validation support.</para>
	/// <para>Add validation support to MvvmLight ViewModelBase by implementing IDataErrorInfo.</para>
	/// </summary>
	public class ViewModelWithErrors : ViewModelBase, IDataErrorInfo
	{
		public ViewModelWithErrors()
		{
			_errorDictionary = new Dictionary<string, List<string>>();
		}

		/// <summary>
		/// <para>Dictionary storing the errors.</para>
		/// <para>The key is the property name, the value is a list of error messages.</para>
		/// </summary>
		private readonly Dictionary<string, List<string>> _errorDictionary;

		/// <summary>
		/// <para>Add an error about a property.</para>
		/// <para>Do nothing if the error is already present.</para>
		/// </summary>
		/// <param name="propertyName">The property for which we add the error.</param>
		/// <param name="error">The error message.</param>
		protected void AddError(string propertyName, string error)
		{
			if (_errorDictionary.ContainsKey(propertyName) == false)
				_errorDictionary[propertyName] = new List<string>();

			if (_errorDictionary[propertyName].Contains(error) == false)
			{
				_errorDictionary[propertyName].Add(error);
			}

		}

		/// <summary>
		/// <para>Remove a previously added error about a property.</para>
		/// <para>Do nothing if the error is not present.</para>
		/// </summary>
		/// <param name="propertyName">The property for which we remove the error.</param>
		/// <param name="error">The error message.</param>
		protected void RemoveError(string propertyName, string error)
		{
			if (_errorDictionary.ContainsKey(propertyName) && _errorDictionary[propertyName].Contains(error))
			{
				_errorDictionary[propertyName].Remove(error);
				if (_errorDictionary[propertyName].Count == 0)
					_errorDictionary.Remove(propertyName);
			}
		}

		/// <summary>
		/// <para>Clear all the errors about a property.</para>
		/// </summary>
		/// <param name="propertyName">The property for which we clear the errors.</param>
		protected void ClearErrors(string propertyName)
		{
			_errorDictionary.Remove(propertyName);
		}

		public string Error
		{
			get { return null; }
		}

		/// <summary>
		/// Get the errors about a property.
		/// </summary>
		/// <param name="propertyName">The property for which we want the errors.</param>
		/// <returns>A concatenation of the errors if any, otherwise null.</returns>
		public string this[string propertyName]
		{
			get
			{
				if (_errorDictionary.ContainsKey(propertyName) == false)
					return null;
				return String.Join(Environment.NewLine, _errorDictionary[propertyName]);
			}
		}
	}
}
